//
//  iCalObserver.m
//  Do Not Disturb
//
//  Created by Chris Karr on 11/8/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "iCalObserver.h"
#import "DNDDefines.h"

@implementation iCalObserver

- (NSString *) getName
{
	return @"iCal";
}

- (void) scan
{
	BOOL iCalOpen = NO;
	
	NSWorkspace * workspace = [NSWorkspace sharedWorkspace];

	NSDictionary * active = [workspace activeApplication];

	if ([[active valueForKey:@"NSApplicationName"] isEqual:@"iCal"])
		iCalOpen = YES;

	NSArray * apps = [workspace launchedApplications];
	
	int i = 0;
	for (i = 0; i < [apps count]; i++)
	{
		if ([[[apps objectAtIndex:i] valueForKey:@"NSApplicationName"] isEqual:@"iCal"])
			iCalOpen = YES;
	}

	if (iCalOpen)
	{
		NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"iCal\"\n\
																			set curevents to \"\"\n\
																			set now to (current date)\n\
																			set theEventSummary to \"None\"\n\
																			repeat with thisCalendar in calendars\n\
																				repeat with thisEvent in ((every event of thisCalendar) whose ((start date ≤ now and end date > now)))\n\
																					set curevents to the summary of thisEvent & \";\"\n\
																				end repeat\n\
																			end repeat\n\
																			return curevents\n\
																		end tell"];

		NSAppleEventDescriptor * desc = [script executeAndReturnError:nil];
		
		if (desc != nil && [desc stringValue] != nil)
		{
			NSArray * events = [[desc stringValue] componentsSeparatedByString:@";"];
			
			NSEnumerator * iter = [events objectEnumerator];
			NSString * event = nil;
			
			while ((event = [iter nextObject]) != nil)
			{
				if (event != nil && ![event isEqualToString:@""])
				{
					NSMutableDictionary * dict = [NSMutableDictionary dictionary];
					[dict setValue:[NSDate date] forKey:@"date"];
					[dict setValue:[NSString stringWithFormat:@"Current iCal Event: %@", event] forKey:@"name"];
	
					[[NSDistributedNotificationCenter defaultCenter] postNotificationName:DND_UPDATE object:@"iCalObserver" userInfo:dict];		
				}
			}
		}
	}
}

@end
